#include "dbnotescount.h"

DbNotesCount::DbNotesCount(QObject *parent) : QObject(parent)
{
    thread = new QThread();
    this->moveToThread(thread);
    thread->start();
}

void DbNotesCount::setDbCommName(const QString &dbCommName)
{
    m_dbCommName = dbCommName;
}

void DbNotesCount::setDbFileName(const QString &dbFileName)
{
    m_dbFileName = dbFileName;
}

void DbNotesCount::query(const QString sql)
{
    QSqlDatabase m_Database;
    // 获取数据库
    if(!QSqlDatabase::contains(m_dbCommName))
    {
        m_Database = QSqlDatabase::addDatabase("QSQLITE", m_dbCommName);
        m_Database.setDatabaseName(m_dbFileName);
    }

    m_Database = QSqlDatabase::database(m_dbCommName);

    if(!m_Database.isOpen())
    {
        m_Database.open();
    }

    //执行查询

    QDateTime dtStart = QDateTime::currentDateTime();

    QSqlQuery query(m_Database);

    int count = 0;
    if(query.exec(sql))
    {
        if(query.next())
        {
            count = query.value(0).toInt();
        }
    }

    if(m_Database.isOpen())
    {
        m_Database.close();
    }

    QDateTime dtEnd = QDateTime::currentDateTime();
    double msec = dtStart.msecsTo(dtEnd);

    emit dbNotesCountQFinished(count, msec);
}


